<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['sbId']" type="hidden"/>
      </a-form-item>

      <row-list :col="2">
        <row-item>
          <a-form-item
            label="工单类别"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select @change="changePlanFlag" v-decorator="['category', {rules: [{required: true, message: '计划性维修不能为空'}]}]" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in planFlagMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="接收时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              showTime
              v-decorator="['repairStartTime']"
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATETIME_PATTERN"
            />
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="完成时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              v-decorator="['repairEndTime']"
              showTime
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATETIME_PATTERN"
            />
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <spare-part-used-select-modal ref="sparePartUsedSelectModal" />
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { changeApplicationForm } from '@/api/repair/application-form'
import { fetchErrorTypeTree } from '@/api/repair/errortype'
import SparePartUsedSelectModal from '@/views/sqarepartmanage/sparepartused/modules/SparePartUsedSelectModal'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'BaseRepairApplicationForm',
  data () {
    return {
      model: null,
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      category: 0,
      planFlagMap: {},
      // 下拉框map
      treeData: [],
      descripitionMap: {},
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      },
      sourceMap: {},
      levelMap: {},
      needStopMap: {},
      statusMap: {}
    }
  },
  components: {
    SparePartUsedSelectModal
  },
  props: {
  },
  created () {
    // 下拉框map
    this.sourceMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIR_APPLICATION_FORM_SOURCE)
    this.levelMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIR_APPLICATION_FORM_LEVEL)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIR_APPLICATION_FORM_STATUS)
    this.needStopMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YES_NO)
    this.descripitionMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIRE_ACTION)
    this.planFlagMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.REPAIR_APPLICATION_FORM_CATEGORY)
  },
  methods: {
    base (record) {
      this.setTree()
      this.visible = true
      this.model = record
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        return
      }
      this.modalTitle = '修改工单'
      const { form: { setFieldsValue } } = this
      // 日期处理
      record.repairStartTime = this.BaseTool.Date.formatter(record.repairStartTime, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      record.repairEndTime = this.BaseTool.Date.formatter(record.repairEndTime, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'sbId',
          'needStop',
          'level',
          'repairContent',
          'category',
          'repairErrorTypeId',
          'repairEndTime',
          'repairStartTime'
        ])))
      })
    },
    getUsers () {

    },
    changePlanFlag (value) {
      this.category = value
      const { form: { setFieldsValue } } = this
      if (this.category === 1) {
        this.$nextTick(() => {
          setFieldsValue({ needStop: 1 })
        })
      } else {
        this.$nextTick(() => {
          setFieldsValue({ needStop: 0 })
        })
      }
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        // 日期处理
        values.repairFileList = this.repairFileList
        values.repairStartTime = this.BaseTool.Date.formatter(values.repairStartTime, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
        values.repairEndTime = this.BaseTool.Date.formatter(values.repairEndTime, this.BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
        changeApplicationForm(values).then(() => {
          this.$message.info('工单已修改。')
          this.handleCancel(values)
        }).catch(() => {
          this.confirmLoading = false
        })
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok')
      }
    },
    handleSbSelect () {
      this.$refs.sbInfoSelectModal.base({}, { filter: 0, status: 2 })
    },
    handleSbSelectd (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'sbId': key,
          'sbName': row.name
        }))
      })
    },
    handlePartSelect () {
      const sbId = this.form.getFieldValue('sbId')
      this.$refs.partInfoSelectModal.base({ sbId })
    },
    handlePartSelected (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'partId': key,
          'partName': row.name
        }))
      })
    },
    /**
     * 设置类别树
     */
    setTree (record = {}) {
      fetchErrorTypeTree({ id: record.id }).then(res => {
        this.treeData = res.data
      })
    },
    handleAddPartUsed () {
      /* const modal = this.$refs.repairFeeModal
      modal.base(null, record) */
      this.$refs.sparePartUsedSelectModal.base(this.model, { sbId: this.model.sbId, modelId: this.model.modelId })
    }

  }
}
</script>
